package handlers

import (
	"fmt"
	"net/http"
	"time"
	"keystone-auth-portal/services"
	
	"github.com/gin-gonic/gin"
)

type DashboardHandler struct {
	keystoneService *services.KeystoneService
	config          map[string]interface{}
}

type ResourceApplication struct {
	ID          string `json:"id"`
	Applicant   string `json:"applicant"`
	ProjectName string `json:"project_name"`
	ResourceType string `json:"resource_type"`
	Description string `json:"description"`
	Status      string `json:"status"`
	CreatedAt   string `json:"created_at"`
	ApprovedBy  string `json:"approved_by,omitempty"`
}

func NewDashboardHandler(keystoneService *services.KeystoneService, config map[string]interface{}) *DashboardHandler {
	return &DashboardHandler{
		keystoneService: keystoneService,
		config:          config,
	}
}

func (h *DashboardHandler) DefaultDashboard(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	// 根据用户角色重定向到对应的控制台
	for _, role := range user.Roles {
		switch role {
		case "project-manager":
			c.Redirect(http.StatusFound, "/dashboard/manager")
			return
		case "team-leader":
			c.Redirect(http.StatusFound, "/dashboard/leader")
			return
		case "developer":
			c.Redirect(http.StatusFound, "/dashboard/developer")
			return
		case "resource-admin":
			c.Redirect(http.StatusFound, "/dashboard/admin")
			return
		}
	}
	
	// 如果没有匹配的角色，显示错误信息
	c.HTML(http.StatusForbidden, "login.html", gin.H{
		"error": "您的账号没有分配有效的系统角色，请联系管理员",
	})
}

func (h *DashboardHandler) ManagerDashboard(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	// 获取项目经理可以管理的所有项目申请
	applications := h.getApplicationsByManager(user.Username)
	
	c.HTML(http.StatusOK, "manager_dashboard.html", gin.H{
		"title":        "项目经理控制台",
		"user":         user,
		"applications": applications,
		"stats":        h.getManagerStats(user.Username),
	})
}

func (h *DashboardHandler) LeaderDashboard(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	// 获取团队负责人项目的申请
	applications := h.getApplicationsByProject(user.ProjectName)
	
	c.HTML(http.StatusOK, "leader_dashboard.html", gin.H{
		"title":        "团队负责人控制台",
		"user":         user,
		"applications": applications,
		"team_members": h.getTeamMembers(user.ProjectName),
	})
}

func (h *DashboardHandler) DeveloperDashboard(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	// 获取开发人员的申请历史
	applications := h.getApplicationsByUser(user.Username)
	
	c.HTML(http.StatusOK, "developer_dashboard.html", gin.H{
		"title":          "开发人员控制台", 
		"user":           user,
		"my_applications": applications,
		"available_resources": h.getAvailableResources(),
	})
}

func (h *DashboardHandler) AdminDashboard(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	c.HTML(http.StatusOK, "admin_dashboard.html", gin.H{
		"title":           "资源管理员控制台",
		"user":            user,
		"all_applications": h.getAllApplications(),
		"system_stats":     h.getSystemStats(),
		"domain_info":      h.getDomainInfo(),
	})
}

func (h *DashboardHandler) SubmitApplication(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	
	resourceType := c.PostForm("resource_type")
	description := c.PostForm("description")
	
	if resourceType == "" || description == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "资源类型和描述不能为空",
		})
		return
	}
	
	// 创建新的资源申请
	application := &ResourceApplication{
		ID:           generateID(),
		Applicant:    user.Username,
		ProjectName:  user.ProjectName,
		ResourceType: resourceType,
		Description:  description,
		Status:       "pending",
		CreatedAt:    getCurrentTime(),
	}
	
	// 保存申请（这里简化为内存存储）
	h.saveApplication(application)
	
	c.JSON(http.StatusOK, gin.H{
		"message": "申请提交成功",
		"application_id": application.ID,
	})
}

func (h *DashboardHandler) ApproveApplication(c *gin.Context) {
	user := c.MustGet("user").(*services.UserContext)
	applicationID := c.Param("id")
	action := c.PostForm("action") // approve 或 reject
	
	application := h.getApplicationByID(applicationID)
	if application == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"error": "申请不存在",
		})
		return
	}
	
	// 验证审批权限
	if !h.canApproveApplication(user, application) {
		c.JSON(http.StatusForbidden, gin.H{
			"error": "没有审批此申请的权限",
		})
		return
	}
	
	// 更新申请状态
	if action == "approve" {
		application.Status = "approved"
	} else {
		application.Status = "rejected"
	}
	application.ApprovedBy = user.Username
	
	h.updateApplication(application)
	
	c.JSON(http.StatusOK, gin.H{
		"message": "处理成功",
	})
}

// 模拟数据存储（实际应用中应该使用数据库）
var applications = make(map[string]*ResourceApplication)

func (h *DashboardHandler) saveApplication(app *ResourceApplication) {
	applications[app.ID] = app
}

func (h *DashboardHandler) getApplicationByID(id string) *ResourceApplication {
	return applications[id]
}

func (h *DashboardHandler) updateApplication(app *ResourceApplication) {
	applications[app.ID] = app
}

func (h *DashboardHandler) getApplicationsByUser(username string) []*ResourceApplication {
	var result []*ResourceApplication
	for _, app := range applications {
		if app.Applicant == username {
			result = append(result, app)
		}
	}
	return result
}

func (h *DashboardHandler) getApplicationsByProject(projectName string) []*ResourceApplication {
	var result []*ResourceApplication
	for _, app := range applications {
		if app.ProjectName == projectName {
			result = append(result, app)
		}
	}
	return result
}

func (h *DashboardHandler) getApplicationsByManager(username string) []*ResourceApplication {
	// 项目经理可以看到所有相关项目的申请
	return h.getAllApplications()
}

func (h *DashboardHandler) getAllApplications() []*ResourceApplication {
	var result []*ResourceApplication
	for _, app := range applications {
		result = append(result, app)
	}
	return result
}

func (h *DashboardHandler) canApproveApplication(user *services.UserContext, app *ResourceApplication) bool {
	// 简化的权限检查逻辑
	for _, role := range user.Roles {
		if role == "team-leader" || role == "project-manager" || role == "resource-admin" {
			return true
		}
	}
	return false
}

func (h *DashboardHandler) getAvailableResources() []string {
	return []string{"虚拟机", "存储卷", "浮动IP", "负载均衡器"}
}

func (h *DashboardHandler) getManagerStats(username string) map[string]interface{} {
	return map[string]interface{}{
		"total_projects":    2,
		"pending_requests":  3,
		"approved_requests": 15,
		"team_members":      8,
	}
}

func (h *DashboardHandler) getTeamMembers(projectName string) []map[string]string {
	return []map[string]string{
		{"name": "dev-li", "role": "developer", "status": "active"},
		{"name": "test-zhao", "role": "tester", "status": "active"},
	}
}

func (h *DashboardHandler) getSystemStats() map[string]interface{} {
	return map[string]interface{}{
		"total_users":    25,
		"active_projects": 8,
		"pending_requests": 12,
		"resource_usage":   75,
	}
}

func (h *DashboardHandler) getDomainInfo() map[string]interface{} {
	return map[string]interface{}{
		"domain_name": h.config["enterprise"].(map[string]interface{})["domain_name"],
		"total_users": 25,
		"total_projects": 8,
	}
}

// 辅助函数
func generateID() string {
	return fmt.Sprintf("app_%d", time.Now().Unix())
}

func getCurrentTime() string {
	return time.Now().Format("2006-01-02 15:04:05")
}